package com.ccsoft.static_package_mult_ds.service;

import com.ccsoft.static_package_mult_ds.dao.order.OrderMapper;
import com.ccsoft.static_package_mult_ds.dao.user.UserMapper;
import com.ccsoft.static_package_mult_ds.entity.Order;
import com.ccsoft.static_package_mult_ds.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionTemplate;

/**
 * @author chanchaw
 * @create 2022-09-17 12:17
 */
@Service
public class TestMultTransactionServiceImpl implements TestMultTransactionService{

    @Autowired
    @Qualifier("orderTransactionTemplate")
    TransactionTemplate orderTransactionTemplate;
    @Autowired
    @Qualifier("userTransactionTemplate")
    TransactionTemplate userTransactionTemplate;

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;
    /**
     * 本方法同时调用两个数据源的写入方法
     * 测试多数据源事务的实现
     * 使用编程式事务
     * @return
     */
    @Override
    public int saveMultDS() {
        orderTransactionTemplate.execute( orderStatus -> {
            userTransactionTemplate.execute( userStatus -> {
                try{
                    insertOrder();
                    insertUser();
//                    int i = 1/0;
                }catch(Exception e){
                    e.printStackTrace();
                    orderStatus.setRollbackOnly();
                    userStatus.setRollbackOnly();
                    return false;
                }
                return true;
            });
            return true;
        });
        return 1;
    }

    private int insertOrder(){
        Order order = new Order();
        order.setOrder_code("2022091701");
        return orderMapper.insertSelective(order);
    }

    private int insertUser(){
        User user = new User();
        user.setSid("mult transaction");
        return userMapper.insertSelective(user);
    }
}
